package com.koron.css2.serviceManage.impl;

import com.koron.css2.InterFaceAction;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.TService;
import com.koron.css2.serviceManage.bean.TServiceDetail;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.TServiceDetailMapper;
import com.koron.css2.serviceManage.mapper.TServiceMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import org.bson.types.ObjectId;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.lang.reflect.Field;
import java.net.InetAddress;
import java.util.List;


public class ServiceUpdate implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {

		@SuppressWarnings("rawtypes")
		MessageBean<List> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", List.class);
		try {
			TService bean = JsonUtils.objectToPojo(req.getData(), TService.class);
			TServiceMapper mapper = factory.getMapper(TServiceMapper.class);
			TServiceDetailMapper detailMapper = factory.getMapper(TServiceDetailMapper.class);

			// 删除该服务下的所有关联明细
			detailMapper.deleteByServiceId(bean.getServiceId());
			// 更新服务信息
			bean.setUpdateName(userInfo.getUserInfo().getName());
			bean.setUpdateTime(CommonUtils.getCurrentTime());
			bean.setIp(InetAddress.getLocalHost().getHostAddress());
			mapper.updateByPrimaryKeySelective(bean);

			for (TServiceDetail detail : bean.gettServiceDetails()) {
				detail.setStatus(1);
				detail.setServiceCode(bean.getServiceCode());
				detail.setDetailId(new ObjectId().toHexString());
				detailMapper.insertSelective(detail);
			}
			// 20220607: 更新接口后将serverMap置空
			InterFaceAction interFaceAction = new InterFaceAction();
			Class<?> test = InterFaceAction.class;
			Field nameField = test.getDeclaredField("serverMap");
			nameField.setAccessible(true);
			nameField.set(interFaceAction,null);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return info;
	}

}
